/*
 * @Description: 
 * @Author: zml
 * @Date: 2025-07-25 09:34:10
 * @LastEditors: zml
 * @LastEditTime: 2025-07-31 15:15:54
 */
import { createSlice } from "@reduxjs/toolkit";
import { asyncRouter } from '../../router';


// 将数据重做
const transformTree = (data: any) => {
  return data.map((item: any) => {
    if (!(item.path === '/login' || item.path === '*')) {
      let obj = {
        key: item.path || '/',
        icon: item.icon,
        label: item.title,
      }
      if (item.children && item.children.length > 0) {
        return Object.assign(obj, { ...obj, children: item.children ? transformTree(item.children) : [] })
      } else {
        return obj
      }
    }
  }).filter((items: any) => items)
}

// 在进行权限判断
const GetPermissions = (data: any, permissions: any) => {
  return data.filter((items => {
    if (permissions.includes(items.key)) {
      if (items.children && items.children.length > 0) {
        items.children = GetPermissions(items.children, permissions);
        return items.children.length > 0 || !items.children;
      }
      return true
    }
  })).map(node => ({ ...node })
  )
}

//创建counterSlice实例并导出
export const userData = createSlice({
  name: 'userData',
  //在创建实例时给定state
  initialState: {
    token: localStorage.getItem('token') || '',
    userinfo: {},
    permissions: [],
    optionList: [],
  },
  // 不能进行异步操作
  reducers: {
    logins: (state, actions) => {
      localStorage.setItem('token', actions.payload.token);
      // redux不会立刻刷新,二次赋值可以解决刷新频繁登录不了问题
      state.token = actions.payload.token
      state.userinfo = {
        username: actions.payload.username,
        password: actions.payload.password,
      }
      state.permissions = actions.payload.permissions
      state.optionList = actions.payload.username == 'admin' ? transformTree(asyncRouter) : GetPermissions(transformTree(asyncRouter), actions.payload.permissions);
    },
  },
});


export const { logins } = userData.actions;

export default userData.reducer;


